import { createSelector, createFeatureSelector } from '@ngrx/store'
import { Cookie } from 'ng2-cookies'
import { AUTH_COOKIE_NAME, REFRESH_TOKEN_COOKIE_NAME, USER_ID } from '../../common/consts'
import { IUser } from '../../core/models'
import { UserActionTypes, UserActions } from '../actions/user'

export interface IState {
  isLogon: boolean
  isRegistered: boolean
  entity: IUser
}

export const initialState: IState = {
  isLogon: false,   // 判断是否已经登录
  isRegistered: false,  // 控制注册窗口和登录窗口
  entity: {
    id: '',
    nickname: '',
    avatar: '',
    email: ''
  }
}

export function reducer (
  state = initialState,
  action: UserActions): IState {
  switch (action.type) {
    case UserActionTypes.LoginSuccess:
    case UserActionTypes.RefreshTokenSuccess:
      const { token, ...userinfo } = action.payload
      const { access_token, expires_in, refresh_token } = token
      Cookie.set(AUTH_COOKIE_NAME, access_token, expires_in / 1000 / 60 / 60 / 24, '/')
      Cookie.set(REFRESH_TOKEN_COOKIE_NAME, refresh_token, 31, '/')
      localStorage.setItem(USER_ID, userinfo.id)
      return {
        ...state,
        isLogon: true,
        entity: {
          ...state.entity,
          ...userinfo
        }
      }
    case UserActionTypes.Logout:
      Cookie.delete(AUTH_COOKIE_NAME)
      Cookie.delete(REFRESH_TOKEN_COOKIE_NAME)
      Cookie.deleteAll('/')
      return initialState
    case UserActionTypes.RegisterSuccess:
      return {
        ...state,
        isRegistered: true
      }
    case UserActionTypes.FetchUserSuccess:
      return {
        ...state,
        isLogon: true,
        entity: {
          ...state.entity,
          ...action.payload
        }
      }
    default:
      return state
  }
}

export const selectEntity = createFeatureSelector<IUser>('entity')
export const selectIsRegistered = createFeatureSelector<boolean>('isRegistered')
export const selectIsLogon = createFeatureSelector<boolean>('isLogon')
